package com.broada.apm.indicator.api.impl;

import java.util.List;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.deletebyquery.DeleteByQueryAction;
import org.elasticsearch.action.deletebyquery.DeleteByQueryRequestBuilder;
import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.es.indices.support.PerfIndicesBuilder;
import com.broada.apm.indicator.api.PerformancePersistanceService;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.indicator.api.model.SearchCondition;
import com.broada.apm.indicator.api.model.SearchConditionComparator;
import com.broada.apm.model.Scope;
import com.broada.apm.model.performance.BasePerformance;
import com.broada.apm.utils.EsClientUtil;
import com.broada.apm.utils.ExceptionUtils;
import com.broada.apm.utils.JsonUtil;

public class EsPerformancePersistanceServicempl implements PerformancePersistanceService {
	private Logger log = LoggerFactory.getLogger(EsPerformancePersistanceServicempl.class);
	private Client client = EsClientUtil.getTransportClient();

	@Override
	public void savePerfs(List<? extends BasePerformance> perfs) {
		try {
			PerfIndicesBuilder perfIncidesBuilder = PerfIndicesBuilder.getInstance();
			if (perfs == null || perfs.size() == 0)
				return;
			BulkRequestBuilder bulkbuilder = client.prepareBulk();
			for (BasePerformance perf : perfs) {
				for (String index : perfIncidesBuilder.getPerfIndices(perf)) {
					bulkbuilder.add(client.prepareIndex(index, Scope.APMRUNNING_PERFS.getType(), perf.getId())
							.setSource(JsonUtil.obj2json(perf)));
				}
			}
			BulkResponse bulkResponse = bulkbuilder.execute().actionGet();
			if (bulkResponse.hasFailures()) {
				ExceptionUtils.error(log, String.format("性能指标对象组保存失败:%s", bulkResponse.buildFailureMessage()),
						new Exception());
			}
		} catch (Exception e) {
			ExceptionUtils.error(log, String.format("性能指标对象组保存失败:%s", e), e);
		}
	}
	@Override
    public boolean clearPerf(String[] index, String type, long timeInMs, String appIds)
            throws ApmDataIndicatorException {
            SearchCondition searchCondition = SearchCondition.newBuilder().add("timestamp", SearchConditionComparator.LTE, timeInMs);
            if(appIds!=null) {
                searchCondition.add("applicationId", SearchConditionComparator.IN, appIds.split(","));
            }
            QueryBuilder queryBuilder = searchCondition.parseCondition();

            DeleteByQueryResponse delete = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE)
            		.setIndices(index)
            		.setTypes(type)
                    .setQuery(queryBuilder)
                    .execute()
                    .actionGet();
            if(delete.getTotalFailed()>Long.valueOf(0)){
          	  return false;
            }
            return true;
    }
	@Override
	public boolean clearDisServicePerf(String[] index, String type, long timeInMs, String[] serviceIds)
            throws ApmDataIndicatorException {
            SearchCondition searchCondition = SearchCondition.newBuilder().add("timestamp", SearchConditionComparator.LTE, timeInMs);
            if(serviceIds!=null) {
                searchCondition.add("serviceId", SearchConditionComparator.NOTIN, serviceIds);
            }
            QueryBuilder queryBuilder = searchCondition.parseCondition();
            
            DeleteByQueryResponse delete = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE)
            		.setIndices(index)
            		.setTypes(type)
                    .setQuery(queryBuilder)
                    .execute()
                    .actionGet();
          if(delete.getTotalFailed()>Long.valueOf(0)){
        	  return false;
          }
          return true;
    }
	
}